package com.langchain4j.core.flow.engine;

import com.langchain4j.core.flow.node.FlowNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 流程节点注册表
 */
@Slf4j
@Component
public class FlowNodeRegistry {
    
    private final Map<String, FlowNode> nodeRegistry = new ConcurrentHashMap<>();
    
    @Autowired
    public FlowNodeRegistry(List<FlowNode> nodes) {
        for (FlowNode node : nodes) {
            registerNode(node);
        }
        log.info("注册了 {} 个流程节点", nodes.size());
    }
    
    /**
     * 注册节点
     * @param node 流程节点
     */
    public void registerNode(FlowNode node) {
        String nodeType = node.getType().name();
        nodeRegistry.put(nodeType, node);
        log.info("注册节点类型: {}", nodeType);
    }
    
    /**
     * 获取节点
     * @param nodeType 节点类型
     * @return 流程节点
     */
    public FlowNode getNode(String nodeType) {
        FlowNode node = nodeRegistry.get(nodeType);
        if (node == null) {
            throw new IllegalArgumentException("未找到节点类型: " + nodeType);
        }
        return node;
    }
    
    /**
     * 获取所有节点类型
     * @return 节点类型列表
     */
    public List<String> getNodeTypes() {
        return List.copyOf(nodeRegistry.keySet());
    }
    
    /**
     * 检查节点类型是否存在
     * @param nodeType 节点类型
     * @return 是否存在
     */
    public boolean hasNodeType(String nodeType) {
        return nodeRegistry.containsKey(nodeType);
    }
    
    /**
     * 创建节点实例
     * @param nodeType 节点类型
     * @param config 节点配置
     * @return 流程节点
     */
    public FlowNode createNode(String nodeType, Map<String, Object> config) {
        FlowNode node = getNode(nodeType);
        
        // 创建新实例并设置配置
        try {
            FlowNode newNode = node.getClass().getDeclaredConstructor().newInstance();
            newNode.setConfig(config);
            return newNode;
        } catch (Exception e) {
            throw new RuntimeException("创建节点实例失败: " + nodeType, e);
        }
    }
} 